package com.zmm.xiaohashu.auth.service.impl;

import com.zmm.framework.common.exception.BizException;
import com.zmm.framework.common.response.Response;
import com.zmm.xiaohashu.auth.constant.RedisKeyConstants;
import com.zmm.xiaohashu.auth.enums.ResponseCodeEnum;
import com.zmm.xiaohashu.auth.model.vo.verificationcode.SendVerificationCodeReqVO;
import com.zmm.xiaohashu.auth.service.VerificationCodeService;
import com.zmm.xiaohashu.auth.sms.AliyunSmsHelper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author: 福禄寿
 * @Date: 2024/9/9 下午5:04
 * @Des: xiaohashu
 **/
@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Resource(name = "taskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private AliyunSmsHelper aliyunSmsHelper;

    @Override
    public Response<?> send(SendVerificationCodeReqVO sendVerificationCodeReqVo) {
        String phone = sendVerificationCodeReqVo.getPhone();

        String key = RedisKeyConstants.buildVerificationCodeKey(phone);

        Boolean isSend = redisTemplate.hasKey(key);
        //判断是否已经发送验证码
        if (isSend) {
            //若之前发送的验证码没有过期，则提示发送验证码频繁
            throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }
        //生成六位随机验证码
        String verificationCode = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));

        //todo : 调用第三方服务
        threadPoolTaskExecutor.submit(() -> {
            String signName = "阿里云短信测试";
            String templateCode = "SMS_279790866";
            String templateParam = String.format("{\"code\":\"%s\"}", verificationCode);
            aliyunSmsHelper.sendMessage(signName, templateCode, phone, templateParam);
        });
        log.info("发送验证码到手机号{}，验证码为{}", phone, verificationCode);

        //存储验证码到redis，设置时间三分钟
        redisTemplate.opsForValue().set(key, verificationCode, 60, TimeUnit.SECONDS);

        return Response.success();
    }
}
